<template>
  <div class="nucleic-ui">
    <div ref="topPart">
      <el-form
        :inline="true"
        size="mini"
        ref="form"
        :model="form"
        class="demo-form-inline"
      >
        <div class="border">
          <el-form-item label="姓名">
            <el-input
              placeholder="请输入姓名"
              v-model="form.name"
              clearable
              @blur="onBlur('form', 'name')"
              @keyup.enter.native="onSubmit"
              style="width: 120px"
            ></el-input>
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input
              placeholder="请输入身份证号"
              v-model="form.idCard"
              clearable
              @blur="onBlur('form', 'idCard')"
              @keyup.enter.native="onSubmit"
            ></el-input>
          </el-form-item>
          <el-form-item label="毕业院校">
            <el-input
              placeholder="请输入毕业院校"
              v-model="form.graduationInstitution"
              clearable
              @blur="onBlur('form', 'graduationInstitution')"
              @keyup.enter.native="onSubmit"
            ></el-input>
          </el-form-item>
          <el-form-item label="专业">
            <el-input
              placeholder="请输入专业"
              v-model="form.speciality"
              clearable
              @blur="onBlur('form', 'speciality')"
              @keyup.enter.native="onSubmit"
              style="width: 120px"
            ></el-input>
          </el-form-item>
          <el-form-item label="学历" v-if="dictData && dictData.education">
            <el-select
              v-model="form.qualification"
              placeholder="请选择"
              @change="eduChange"
              style="width: 140px; margin-right: 10px"
            >
              <el-option
                v-for="item in dictData.education"
                :key="'education' + item.value"
                :label="item.value"
                :value="item.key"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="form.qualificationSub"
              placeholder="请选择"
              style="width: 140px"
            >
              <el-option
                v-for="item in eduList"
                :key="'education' + item.value"
                :label="item.value"
                :value="item.key"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据来源" v-if="dictData && dictData.sources">
            <el-select
              v-model="form.sources"
              placeholder="请选择"
              style="width: 140px"
            >
              <el-option
                v-for="item in dictData.sources"
                :key="'sources' + item.value"
                :label="item.value"
                :value="item.key"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" v-if="dictData && dictData.status">
            <el-select
              v-model="form.status"
              placeholder="请选择"
              style="width: 140px"
            >
              <el-option
                v-for="item in dictData.status"
                :key="'status' + item.value"
                :label="item.value"
                :value="item.key"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="danger"
              @click="onReadIDCard"
              icon="el-icon-postcard"
              size="mini"
              >读卡</el-button
            >
            <el-button
              type="primary"
              @click="onSubmit"
              icon="el-icon-search"
              size="mini"
              >搜索</el-button
            >
            <el-button
              type="info"
              @click="onAddFiles"
              icon="el-icon-add"
              size="mini"
              v-if="page == 'add'"
              >新增档案</el-button
            >
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              >导出</el-button
            >
          </el-form-item>
          <!-- <el-form-item>
        <el-button type="info" @click="onResetFun" icon="el-icon-refresh" size="mini">重置</el-button>
      </el-form-item> -->
        </div>
      </el-form>
    </div>
    <div class="nucleic-scroll">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        v-if="theight"
        :height="theight"
      >
        <el-table-column
          prop="index"
          label="序号"
          width="70"
          align="center"
          fixed="left"
        >
        </el-table-column>

        <el-table-column
        fixed="left"
          prop="name"
          label="姓名"
          align="center"
          width="100"
        >
        </el-table-column>
        <el-table-column
          fixed="left"
          prop="idCard"
          label="身份证号"
          align="center"
          width="200"
        >
        </el-table-column>
        <el-table-column prop="sex" label="性别" align="center" width="100">
        </el-table-column>
        <el-table-column
          prop="qualification"
          label="学历"
          width="140"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="phone"
          label="联系方式"
          width="140"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="speciality"
          label="专业"
          width="140"
          align="center"
        >
        </el-table-column>

        <el-table-column
          label="毕业院校"
          width="140"
          align="center"
        >
          <template slot-scope="scope">
            <span class="nativePlace" :title="scope.row.graduationInstitution">{{
              scope.row.graduationInstitution
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="graduationTime"
          label="毕业时间"
          width="140"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="partyMemberTag"
          label="是否为党员"
          width="140"
          align="center"
        >
        </el-table-column>

        <el-table-column
          prop="partyMembershipTime"
          label="入党时间"
          width="140"
          align="center"
        >
        </el-table-column>

        <el-table-column
          prop="punishmentTag"
          label="是否受到处分"
          width="100"
          align="center"
        >
        </el-table-column>
        <el-table-column label="籍贯" width="140" align="center">
          <template slot-scope="scope">
            <span class="nativePlace" :title="scope.row.nativePlace">{{
              scope.row.nativePlace
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="家庭住址" width="140" align="center">
          <template slot-scope="scope">
            <span class="nativePlace" :title="scope.row.address">{{
              scope.row.address
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="position"
          label="位置"
          width="140"
          align="center"
        >
        </el-table-column>
        <el-table-column label="附件统计" width="140" align="center">
          <template slot-scope="scope">
            <span class="nativePlace" :title="scope.row.attachmentStatistics">{{
              scope.row.attachmentStatistics
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="notes" label="备注" width="200">
        </el-table-column>
        <el-table-column
          prop="warehousingTime"
          label="入库时间"
          width="160"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="lastOperationTime"
          label="最后一次编辑时间"
          width="160"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="operator"
          label="操作者"
          width="120"
          align="center"
        >
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <span
              :class="
                scope.row.status == 0
                  ? 'nucleic-st-normal'
                  : scope.row.status == 1
                  ? 'nucleic-st-exce'
                  : 'nucleic-st-exc'
              "
              >{{ scope.row.status == 0 ? "在档" : "已提档" }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="sources" label="数据来源" width="140">
        </el-table-column>

        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          width="200"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <template v-if="page == 'add' && scope.row.status == 0">
              <el-button
                size="mini"
                @click="editFun(scope.row, false)"
                type="text"
                icon="el-icon-edit"
                >编辑</el-button
              >
              <el-button
                size="mini"
                @click="deleteFun(scope.row)"
                type="text"
                icon="el-icon-delete"
                >删除</el-button
              >
              <el-button
                size="mini"
                @click="editFun(scope.row, true)"
                type="text"
                icon="el-icon-upload2"
                >上传资料</el-button
              >
            </template>
            <template
              v-if="
                page == 'query' ||
                (page == 'add' && scope.row.status == 1) ||
                (page == 'upshifting' && scope.row.status == 1)
              "
            >
              <el-button
                size="mini"
                @click="viewDetail(scope.row)"
                type="text"
                icon="el-icon-view"
                >详情</el-button
              >
            </template>
            <template v-if="page == 'upshifting' && scope.row.status == 0">
              <el-button
                size="mini"
                @click="viewDetail(scope.row)"
                type="text"
                icon="el-icon-setting"
                >提档</el-button
              >
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-row class="pages" :gutter="10" v-if="datadep == 1">
      <el-col :span="24">
        <div style="text-algin: center">
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="pageNum"
            :limit.sync="pageSize"
            :pageSizes="pageSizes"
            @pagination="getTableThird"
          />
          <!-- </el-pagination> -->
        </div>
      </el-col>
    </el-row>
    <div class="files-add-window" v-if="isAddFiles">
      <add-person
        ref="addPerson"
        :websocket="websocket"
        :dictData="dictData"
        :id="id"
        :onlyUpload="onlyUpload"
        :isAdd="isAdd"
        @closeAddFiles="closeAddFiles"
        v-if="isAddFiles"
      />
    </div>
    <div class="files-add-window" v-if="isDet">
      <Detail
        :id="id"
        :page="page"
        @closeDetail="closeDetail"
        @getTableThird="getTableThird"
      />
    </div>
  </div>
</template>
<script>
import { getTableThird, deleteTr, educationSub } from "@/api/files/basics";
import { dictData } from "@/api/index";
import { CreateWebSocket, ReadIDCard, CloseConnect } from "@/api/readCard";
import { getToken } from "@/utils/auth";
import AddPerson from "../components/addPerson.vue";
import Detail from "../components/detail.vue";
export default {
  name: "Common",
  components: { AddPerson, Detail },
  props: ["page"],
  data() {
    return {
      loading: false,
      datadep: 1, //1全部数据 2异常数据
      // 总条数
      total: 0,
      //每一页显示数目
      pageSize: 50,
      //第几页
      pageNum: 1,
      pageSizes: [50, 100, 150, 200],
      result: null,
      form: {
        name: "", //人员姓名
        idCard: "", //身份证号
        speciality: "", //专业
        qualification: "", //
        qualificationSub: "",
        sources: "",
        status: "",
        orderByColumn: "", //排序
        isAsc: "desc", //排序方式 desc：降序 asc：升序
      },
      formOrg: {
        name: "", //人员姓名
        idCard: "", //身份证号
        speciality: "", //专业
        qualification: "", //
        qualificationSub: "",
        sources: "",
        status: "",
        orderByColumn: "", //排序
        isAsc: "desc", //排序方式 desc：降序 asc：升序
      },
      personnelIdentityList: [], //人员身份
      batchDateList: [], //批次号--含有全部
      batchDateList2: [], //批次号--不含有全部
      tableData: [],
      //详情
      dialogVisible: false,
      details: {},
      family: [],
      //tab
      activeName: "first",
      //上传
      file: "",
      //校验excel
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API +
          "/dataAnalysis/v2/common/basedata/import", // todo
      },
      uploadData: {
        dataType: 1,
        batchNumber: "",
      },
      deleteData: {
        batchNumber: "",
      },
      statusDataMsg: "",
      //编辑
      dialogForm: {
        id: "",
        name: "",
        idCard: "",
        township: "",
        village: "",
        notes: "",
      },
      //历史修改数据
      hisDialogVisibles: {
        flag: false,
        tableData: [],
        total: 0,
        //每一页显示数目
        pageSize: 10,
        //第几页
        pageNum: 1,
        pageSizes: [10, 20, 30, 40],
      },
      //导入错误信息查询
      dialogVisibles: {
        flag: false,
        tableData: [],
        total: 0,
        //每一页显示数目
        pageSize: 10,
        //第几页
        pageNum: 1,
        pageSizes: [10, 20, 30, 40],
      },
      dialogDetails: {
        flag: false,
        tableData: [],
        total: 0,
        //每一页显示数目
        pageSize: 10,
        //第几页
        pageNum: 1,
        pageSizes: [10, 20, 30, 40],
      },
      time: null,
      errFileName: "",
      defaultSelected: "",
      multipleSelection: [],
      dialogDelete: false,
      theight: "",
      resizeFlag: null,
      isAddFiles: false,
      websocket: null,
      dictData: null,
      id: "",
      onlyUpload: false,
      isAdd: false,
      isDet: false,
      eduList: [],
    };
  },
  created() {
    this.getDictData();
  },
  methods: {
    onReadIDCard() {
      ReadIDCard(this.websocket);
    },
    onBlur(key1, key) {
      this[key1][key] = this[key1][key] ? this[key1][key].trim() : "";
    },
    //新增档案
    onAddFiles() {
      this.id = "";
      this.isAddFiles = true;
      this.onlyUpload = false;
      this.isAdd = true;
    },
    closeAddFiles(type) {
      this.isAddFiles = false;
      if (!type) {
        this.form = JSON.parse(JSON.stringify(this.formOrg));
        this.onSubmit();
      }
    },
    getDictData() {
      let params = {};
      dictData(params).then((res) => {
        if (res.code == 200) {
          this.dictData = res.data;
          this.onSubmit();
        } else {
          this.$message.warning(res.msg);
        }
      });
    },
    getEducationSub(name) {
      let data = {
        name: name,
      };
      educationSub(data).then((res) => {
        if (res.code == 200) {
          this.eduList = res.data;
        }
      });
    },
    eduChange(value) {
      this.getEducationSub(value);
    },
    editFun(row, bool) {
      this.isAddFiles = true;
      this.id = row.id;
      this.onlyUpload = bool;
      this.isAdd = false;
    },

    deleteFun(row) {
      const userIds = row.id;
      this.$modal
        .confirm('是否确认删除用户为"' + row.name + '"的数据项？')
        .then(function () {
          return deleteTr(userIds);
        })
        .then(() => {
          this.getTableThird();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    onExcelThird() {
      this.upload.title = "Excel导入"; // todo
      this.upload.open = true;
      this.uploadData.batchNumber = "";
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      //this.getTable();
      let { batchNumber } = this.uploadData;

      this.form.params.beginBatchNumber = batchNumber;
      this.form.params.endBatchNumber = batchNumber;
      this.datadep = 1;
      this.getBatchHistoryList();
      //this.getDasedataStatus(batchNumber);
    },
    // 提交上传文件
    submitFileForm() {
      if (this.uploadData.batchNumber) {
        this.$refs.upload.submit();
      } else {
        this.$modal.msgWarning("请选择批次号");
      }
    },
    cancleFileForm() {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
    },
    getTableThird() {
      let data = this.form;
      this.loading = true;
      getTableThird(data, this.pageNum, this.pageSize)
        .then((res) => {
          if (res.code == 200) {
            let { rows, total } = res;
            rows.map((item, index) => {
              item.index = (this.pageNum - 1) * this.pageSize + index + 1;
              return item;
            });
            this.tableData = rows;
            this.total = total;
          } else {
            this.tableData = [];
            this.total = 0;
          }
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          this.tableData = [];
          this.total = 0;
        });
    },
    //查询数据1
    onSubmit() {
      this.loading = false;
      this.tableData = [];
      this.pageNum = 1;
      this.total = 0;
      this.getTableThird();
    },

    downloadDetail(event) {
      if (event.target.nodeName === "A") {
        let data = {
          fileName: this.errFileName,
        };
        this.downloadGet(
          "/dataAnalysis/v2/common/basedata/errfile/download",
          data,
          `${this.form.params.beginBatchNumber}_${new Date().getTime()}.xlsx`
        );
      }
    },
    onResetFun() {
      this.form.name = "";
      this.form.idCard = "";
      this.form.qualification = "";
      this.form.speciality = "";
      this.form.sources = "";
      this.form.status = "";
      this.getTableThird();
    },
    //查看详情
    viewDetail(row) {
      this.isDet = true;
      this.id = row.id;
    },
    closeDetail() {
      this.isDet = false;
    },
    async update() {
      let h =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight; //浏览器高度
      let topH = this.$refs.topPart.offsetHeight;

      let tableHeight = h - topH - 84 - 150;
      this.theight = tableHeight;
      //console.log(h, this.theight);
      await this.$nextTick();
    },
    getEventData(data) {
      if (!this.isAddFiles) {
        console.log("页面调用common");
        console.log(data);
        this.form = JSON.parse(JSON.stringify(this.formOrg));
        if (data) {
          let dArr = data.split("|");
          this.form.name = dArr[0].split(":")[1];
          this.form.idCard = dArr[5] ? dArr[5] : "";
        }
        console.log(this.form);
      } else {
        this.$refs.addPerson.getEventData(data);
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      let filename = "档案";
      if (this.page == "add") {
        filename = filename + "新增";
      } else if (this.page == "query") {
        filename = filename + "查询";
      } else if (this.page == "upshifting") {
        filename = filename + "提档";
      }
      this.download(
        "archive/personnel/export",
        {
          ...this.form,
        },
        `档案_${new Date().getTime()}.xlsx`
      );
    },
  },
  mounted() {
    let _this = this;
    this.websocket = CreateWebSocket(this.getEventData);
    //console.log("测试：" + this.$globalData.webSocket);
    // if(!this.$globalData.webSocket){
    //   CreateWebSocket(this.getEventData);
    // }
    _this.update();
    window.onresize = () => {
      if (_this.resizeFlag) {
        clearTimeout(_this.resizeFlag);
      }
      _this.resizeFlag = setTimeout(() => {
        _this.update();
        _this.resizeFlag = null;
      }, 100);
    };
  },
  beforeDestroy() {
    clearTimeout(this.time);
    CloseConnect(this.websocket);
  }, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.nativePlace {
  width: 100%;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.border {
  position: relative;
  &::after {
    content: "";
    position: absolute;
    width: 100%;
    border-bottom: 2px solid #ccc;
    left: 0;
    bottom: 0;
  }
}
.nucleic-ui {
  padding: 20px;
  .nucleic-fixed {
    position: fixed;
    top: 80px;
  }
  .pages {
    font-size: 14px;
    color: #333;
    span {
      color: #009688;
    }
    padding: 20px 0;
  }
  .nucleic-scroll {
    width: 100%;
    overflow: auto;
  }
}
.export-dialog {
  width: 100%;
  .detail-title {
    font-size: 14px;
    color: #333;
  }
  p {
    color: #999;
    font-size: 12px;
  }
}
.nucleic-st {
  &-normal {
    color: #606266;
  }
  &-exce {
    color: #f56c6c;
  }
  &-exc {
    color: #409eff;
  }
}
.nucleic-upload {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .text-center {
    margin-left: 10px;
  }
}
.nucleic-imp {
  overflow: hidden;
  clear: both;
  &-msg {
    float: left;
    font-size: 14px;
    > span {
      cursor: pointer;
    }
  }
  &-btn {
    float: right;
  }
}
.files-add-window {
  position: absolute;
  right: 0;
  top: 0;
  width: 100%;
  height: calc(100vh - 80px);
  background: #fff;
  z-index: 99;
}
</style>
<style rel="stylesheet/scss" lang="scss">
.n-dl {
  color: #409eff;
  cursor: pointer;
  &:hover {
    color: #409eff;
  }
}

.demo-form-inline.el-form--inline .el-form-item__label {
  float: left;
}
</style>
